import { defineStore } from 'pinia'
import type { Store } from './types'
import APIShopkeeper from '@/api/shopkeeper/index'

export const useSocket = defineStore('socket', {
    state: (): Store => ({
        socket: null,
    }),
    actions: {
        initSocket() {
            this.socket = new WebSocket(import.meta.env.VITE_APP_WS_URL)
            this.socket.addEventListener('open', (event) => {
                console.log('客户端已连接上!')
                this.socket?.send('hello server,this is client!') //客户端给服务端推送消息
            })

            this.socket.addEventListener('message', (e) => {
                const data = JSON.parse(e.data)
                const type = data.type
                switch (type) {
                    case 'init':
                        APIShopkeeper.sendWsMessage({
                            type: 'init',
                            client_id: data.client_id
                        })
                        console.log('socket 已发送初始化用户数据')
                        break
                }
            })

            this.socket.addEventListener('close', (event) => {
                console.log("连接已关闭")
            })
        }
    }
})
